import {Component, inject, OnInit} from '@angular/core';
import {FormControl, FormGroup, NonNullableFormBuilder, ReactiveFormsModule, Validators} from "@angular/forms";
import {NZ_MODAL_DATA, NzModalComponent, NzModalModule, NzModalRef} from "ng-zorro-antd/modal";
import {NzFormControlComponent, NzFormItemComponent, NzFormLabelComponent, NzFormModule} from "ng-zorro-antd/form";
import {NzInputDirective, NzInputGroupComponent} from "ng-zorro-antd/input";
import {NzGridModule} from "ng-zorro-antd/grid";
import {NzInputNumberComponent} from "ng-zorro-antd/input-number";
import {AsyncPipe} from "@angular/common";
import {User} from "../../@core/data/user";
import {NzMessageService} from "ng-zorro-antd/message";
import {UserService} from "../user.service";
import {NzButtonComponent} from "ng-zorro-antd/button";

interface UserModalData {
  isEdit: boolean,
  user?: User
}

@Component({
  selector: 'user-modal',
  templateUrl: './user-modal.component.html',
  styleUrl: './user-modal.component.css',
  standalone: true,
  imports: [
    NzModalComponent,
    NzFormModule,
    NzModalModule,
    ReactiveFormsModule,
    NzFormItemComponent,
    NzFormLabelComponent,
    NzFormControlComponent,
    NzInputGroupComponent,
    NzInputNumberComponent,
    NzInputDirective,
    AsyncPipe,
    NzButtonComponent,
    NzGridModule
  ]
})
export class UserModalComponent implements OnInit {

  private readonly userModalData: UserModalData = inject(NZ_MODAL_DATA)
  readonly #modal = inject(NzModalRef)
  validateForm: FormGroup<{
    id: FormControl<string>;
    username: FormControl<string>;
    password: FormControl<string>;
    realName: FormControl<string>;
    age: FormControl<number>;
    address: FormControl<string>;
  }> = this.fb.group({
    id: [''],
    username: ['', [Validators.required]],
    password: ['', [Validators.required]],
    realName: ['', [Validators.required]],
    age: [20, [Validators.required, Validators.min(0), Validators.max(130)]],
    address: ['', [Validators.required]]
  });

  constructor(private fb: NonNullableFormBuilder,
              private userService: UserService,
              private messageService: NzMessageService) {
  }

  ngOnInit(): void {
    if (this.userModalData.user) {
      let { user } = this.userModalData
      this.validateForm.patchValue({
        id: user.id,
        username: user.username,
        password: '',
        realName: user.realName,
        age: user.age,
        address: user.address
      })
    }
  }

  handleCancel() {
    this.#modal.close()
  }

  handleOk() {
    // 校验表单
    if (!this.validForm()) {
      return;
    }
    let user = this.validateForm.value as User
    let { isEdit } = this.userModalData
    if (isEdit) {
      // 执行修改
      this.userService.editUser(user)
        .subscribe({
            next: () => {
              this.messageService.success('修改成功')
            },
            error: (error) => {
              this.messageService.error('修改失败：' + error.message)
              return
            }
          }
        )
    } else {
      // 执行新增
      this.userService.addUser(user)
        .subscribe({
            next: () => {
              this.messageService.success('新增成功')
            },
            error: (error) => {
              this.messageService.error('新增失败：' + error.message)
              return
            }
          }
        )
    }
    // 执行成功，关闭模态框
    this.#modal.close(user)
  }

  /**
   * 验证表单
   */
  validForm(): boolean {
    if (this.validateForm.valid) {
      console.log('验证表单', this.validateForm.value);
      return true;
    } else {
      // 显示表单验证错误
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
      return false;
    }
  }

}
